﻿package com.thorqq.magictimer.widget;


import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

public class LineBreakLayout extends ViewGroup
{
    private final static int VIEW_MARGIN = 10;
    private int mMargin = VIEW_MARGIN;

    public LineBreakLayout(Context context)
    {
        super(context);
        setWillNotDraw(false);
    }

    public LineBreakLayout(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        setWillNotDraw(false);
    }
    
    public void setViewMargin(int margin)
    {
        mMargin = margin;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        // Log.d(TAG, "widthMeasureSpec = " + widthMeasureSpec+
        // " heightMeasureSpec" + heightMeasureSpec);
        for (int index = 0; index < getChildCount(); index++)
        {
            final View child = getChildAt(index);
            // measure
            child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
        }

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        int left   = l + super.getPaddingLeft();
        int top    = t + super.getPaddingTop();
        int right  = r - super.getPaddingRight();
        
//        int bottom = b + super.getPaddingBottom();
//
//        Util.log("LineBreakLayout.onLayout: " + left + ", "
//                + top + ", "
//                + right + ", "
//                + bottom);

        final int count = getChildCount();
        int row = 0;// which row lay you view relative to parent
        int lengthX = left; // right position of child relative to parent
        int lengthY = top; // bottom position of child relative to parent
        
        
        for (int i = 0; i < count; i++)
        {

            final View child = this.getChildAt(i);
            int width = child.getMeasuredWidth();
            int height = child.getMeasuredHeight();
            lengthX += width + mMargin;
            lengthY = row * (height + mMargin) + mMargin + height + top;
            // if it can't drawing on a same line , skip to next line
            if (lengthX > right)
            {
                lengthX = width + mMargin + left;
                row++;
                lengthY = row * (height + mMargin) + mMargin + height + top;
            }

            child.layout(lengthX - width, lengthY - height, lengthX, lengthY);
//            Util.log("l,t,r,b: " + (lengthX - width) + ", "
//                    + (lengthY - height) + ", "
//                    + (lengthX) + ", "
//                    + (lengthY));
        }
        
        super.setMinimumHeight(lengthY + super.getPaddingBottom());
    }

}